﻿using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Configuration;

namespace EC.Merchant.Controllers
{
    using EC.Application.Interface;
    using EC.Entity;
    using EC.Entity.Enum;
    using EC.Entity.Response.IpTable;
    using EC.Util;

    /// <summary>
    /// 基础控制
    /// </summary>
    public class BaseController : Controller
    {
        #region 注入
        /// <summary>
        /// 用户编号
        /// </summary>
        public int UserId;

        /// <summary>
        /// 商户编号
        /// </summary>
        public int MerchantId;
        
        /// <summary>
        /// 用户名称
        /// </summary>
        public string UserName;

        /// <summary>
        /// 功能权限
        /// </summary>
        public List<string> UserPermissions;


        private readonly LoginService _loginService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dataBase">菜单</param>
        public BaseController(LoginService loginService)
        {
            _loginService = loginService;
        }
        #endregion

        /// <summary>
        /// OnActionExecuting
        /// </summary>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var isAjaxRequest = context.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";

            //获取ip地址
            //string ipaddress = context.HttpContext.Connection.RemoteIpAddress.ToString();
            //IList<IpTableCacheEntity> ips = _loginService.GetIptable((int)SystemType.商户管理);
            //if (!ips.Any(c => c.Ip.Contains(ipaddress.Replace("::ffff:", ""))))
            //{
            //    context.Result = Json(new
            //    {
            //        IsLogout = false,
            //        Message = "请联系管理人员加白",
            //    });
            //}


            if (HttpContext.User.Claims != null && HttpContext.User.Identity.IsAuthenticated && HttpContext.User.Claims.Count() == 3)
            {
                var permissions = EncryptionUtil.DeCryptDES(string.Join(", ", HttpContext.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role).Value));
                //获取用户编号
                this.UserId = int.Parse(HttpContext.User.Claims.First().Value);
                this.MerchantId = int.Parse(HttpContext.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.DenyOnlySid).Value);
                this.UserPermissions = new List<string>(permissions.Split(','));
            }
            else
            {
                if (isAjaxRequest)
                {
                    context.Result = Json(new
                    {
                        IsLogout = true,
                        Message = "登录超时，请重新登录",
                    });
                }
                else
                {
                    context.Result = new ViewResult { ViewName = "~/Views/Account/Index.cshtml" };
                }
            }

            base.OnActionExecuting(context);
        }
    }

    /// <summary>
    /// 自定义方法拦截器
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class AuthFilter : ActionFilterAttribute
    {
        /// <summary>
        /// 授权码列表
        /// </summary>
        public AuthCode[] Code { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="code">权限码</param>
        public AuthFilter(params AuthCode[] code)
        {
            this.Code = code;
        }

        /// <summary>
        /// 调用后执行
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var isAjaxRequest = context.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";

            if (context.HttpContext.User.Claims != null && context.HttpContext.User.Claims.Any() && context.HttpContext.User.Claims.Count() == 3)
            {
                var userId = context.HttpContext.User.Claims.First().Value;
                if (!string.IsNullOrEmpty(userId))
                {
                    try
                    {
                        var permissions = EncryptionUtil.DeCryptDES(context.HttpContext.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role).Value);
                        if (!string.IsNullOrEmpty(permissions))
                        {
                            var isAuthority = Code.Any(item => permissions.Contains(item.ToString()));
                            if (!isAuthority)
                            {
                                if (isAjaxRequest)
                                {
                                    var result = new JsonResult(new JResult
                                    {
                                        Success = false,
                                        Message = "您没有权限访问",
                                        Callback = "FlashPay.UI.CloseDialog();FlashPay.UI.NoPrivilege()"
                                    });
                                    context.Result = result;
                                }
                                else
                                {
                                    context.Result = new ViewResult { ViewName = "ErrorPrivilege" };
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (isAjaxRequest)
                        {
                            var result = new JsonResult(new JResult
                            {
                                Success = false,
                                Message = "您没有权限访问",
                                Callback = "FlashPay.UI.NoPrivilege()"
                            });
                            context.Result = result;
                        }
                        else
                        {
                            context.Result = new ViewResult { ViewName = "ErrorPrivilege" };
                        }
                    }
                }
            }
        }
    }
}
